home *** CD-ROM | disk | FTP | other *** search
/ Turnbull China Bikeride / Turnbull China Bikeride - Disc 2.iso / STUTTGART / FROMUTS / XLISP1 / lisp / QUEENS < prev    next >
Lisp/Scheme  |  1990-02-23  |  2KB  |  49 lines

  1. ;
  2. ; Place n queens on a board
  3. ;  See Winston and Horn Ch. 11
  4. ;
  5. ; Usage:
  6. ;       (queens <n>)
  7. ;          where <n> is an integer -- the size of the board - try (queens 4)
  8.  
  9. (defun cadar (x)
  10.   (car (cdr (car x))))
  11.  
  12. ; Do two queens threaten each other ?
  13. (defun threat (i j a b)
  14.   (or (equal i a)                       ;Same row
  15.       (equal j b)                       ;Same column
  16.       (equal (- i j) (- a b))           ;One diag.
  17.       (equal (+ i j) (+ a b))))         ;the other diagonal
  18.  
  19. ; Is poistion (n,m) on the board safe for a queen ?
  20. (defun conflict (n m board)
  21.   (cond ((null board) nil)
  22.         ((threat n m (caar board) (cadar board)) t)
  23.         (t (conflict n m (cdr board)))))
  24.  
  25.  
  26. ; Place queens on a board of size SIZE
  27. (defun queens (size)
  28.   (prog (n m board)
  29.         (setq board nil)
  30.         (setq n 1)                      ;Try the first row
  31.         loop-n
  32.         (setq m 1)                      ;Column 1
  33.         loop-m
  34.         (cond ((conflict n m board) (go un-do-m))) ;Check for conflict
  35.         (setq board (cons (list n m) board))       ; Add queen to board
  36.         (cond ((> (setq n (1+ n)) size)            ; Placed N queens ?
  37.                (print (reverse board))))           ; Print config
  38.         (go loop-n)                                ; Next row which column?
  39.         un-do-n
  40.         (cond ((null board) (return 'Done))        ; Tried all possibilities
  41.               (t (setq m (cadar board))            ; No, Undo last queen placed
  42.                  (setq n (caar board))
  43.                  (setq board (cdr board))))
  44.  
  45.         un-do-m
  46.         (cond ((> (setq m (1+ m)) size)          ; Go try next column
  47.                (go un-do-n))
  48.               (t (go loop-m)))))
  49.